﻿@inject IHttpService _httpService
@inject IPopupService PopupService


@if (Model == null)
{
    <MDCard>
        <MCardText Class="pt-8 pb-8">
            <CnGalWebSite.Components.Progressings.ProgressingCard />
        </MCardText>
    </MDCard>
}
else
{
    <MDCard>
        <MCardTitle>
            @(Id==0? $"添加{_name}" : $"编辑{_name}")  @Model.EntryName
        </MCardTitle>
        <MCardText>
            Id：@Model.Id
        </MCardText>
        <MCardText>
            <MRow>
                <MCol Cols="12" Md="6">
                    <CnGalWebSite.Components.Inputs.MasaSelecte @bind-Value="Model.Reason" TValue="RecommendReason" Label="推荐理由" />
                </MCol>
                <MCol Cols="12" Md="6">
                    <MTextField @bind-Value="Model.EntryId" Label="词条Id" />
                </MCol>
                <MCol Cols="12" Md="6">
                    <MCheckbox @bind-Value="Model.IsHidden" Label="是否隐藏" />
                </MCol>
            </MRow>

        </MCardText>
        <MCardActions Class="pb-6 ps-6 pe-6">
            <MSpacer></MSpacer>
            <MButton Color="primary"
                     Text
                     OnClick="SaveEdit">
                <MIcon Left>mdi-check</MIcon>
                保存
            </MButton>
        </MCardActions>

    </MDCard>

}



@code {
    [Parameter]
    public long Id { get; set; }
    [Parameter]
    public EventCallback OnEdited { get; set; }

    RecommendEditModel Model;

    private string _baseUrl = "api/recommends/";
    private string _name = "推荐";


    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await Refresh();
    }

    public async Task Refresh()
    {
        try
        {
            Model = null;
            StateHasChanged();
            Model = Id == 0 ? new RecommendEditModel() : await _httpService.GetAsync<RecommendEditModel>($"{_baseUrl}edit?id={Id}");
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, $"获取{_name}信息失败");
        }
    }

    public async Task SaveEdit()
    {
        try
        {
            var result = await _httpService.PostAsync<RecommendEditModel, Result>($"{_baseUrl}edit", Model);
            if (result.Successful)
            {
                if (!string.IsNullOrWhiteSpace(result.Error))
                {
                    await PopupService.ToastAsync(result.Error, AlertTypes.Success);
                }
                await OnEdited.InvokeAsync(Model);
                StateHasChanged();
            }
            else
            {
                await PopupService.ToastAsync(result.Error ?? "操作失败", AlertTypes.Error);
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, Model.Id == 0 ? $"添加{_name}失败" : $"编辑{_name}信息失败");
        }

    }
}
